package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.controller.dto.AiChatRequest;
import cn.edu.tju.elm.controller.dto.AiChatResponse;
import cn.edu.tju.elm.controller.dto.AiChatHistoryRequest;
import cn.edu.tju.elm.controller.dto.AiChatMessageDto;
import cn.edu.tju.elm.controller.dto.AiChatHistoryResponse;
import cn.edu.tju.elm.model.AiChatMessage;
import cn.edu.tju.elm.service.AiChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/ai")
@Tag(name = "AI聊天管理", description = "提供AI聊天、多轮对话、历史记录等功能")
public class AiChatController {

    @Autowired
    private AiChatService aiChatService;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * AI聊天接口
     */
    @PostMapping("/chat")
    @Operation(summary = "AI聊天", description = "发送消息给AI并获取回复，支持多轮对话")
    public HttpResult<AiChatResponse> chat(@RequestBody AiChatRequest request) {
        try {
            // 验证请求参数
            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "消息内容不能为空");
            }
            if (request.getUserId() == null) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "用户ID不能为空");
            }

            // 如果是新的对话，生成会话ID
            String sessionId = request.getSessionId();
            if (sessionId == null || sessionId.trim().isEmpty()) {
                sessionId = aiChatService.generateSessionId();
            }

            log.info("AI聊天请求，用户ID: {}, 会话ID: {}", request.getUserId(), sessionId);

            // 调用AI服务
            String aiReply = aiChatService.sendMessageToAi(
                    request.getMessage(), 
                    sessionId, 
                    request.getUserId()
            );

            // 构建响应
            AiChatResponse response = new AiChatResponse();
            response.setReply(aiReply);
            response.setSessionId(sessionId);
            response.setTimestamp(LocalDateTime.now().format(DATE_TIME_FORMATTER));

            return HttpResult.success(response);

        } catch (Exception e) {
            log.error("AI聊天失败", e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "AI聊天失败: " + e.getMessage());
        }
    }

    /**
     * 获取聊天历史
     */
    @GetMapping("/history/{sessionId}")
    @Operation(summary = "获取聊天历史", description = "获取指定会话的聊天历史记录")
    public HttpResult<AiChatHistoryResponse> getChatHistory(
            @PathVariable String sessionId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        try {
            if (sessionId == null || sessionId.trim().isEmpty()) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "会话ID不能为空");
            }
            if (userId == null) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "用户ID不能为空");
            }

            log.info("获取聊天历史，用户ID: {}, 会话ID: {}, 页码: {}, 每页条数: {}", 
                    userId, sessionId, page, pageSize);

            // 创建分页对象
            Pageable pageable = PageRequest.of(page - 1, pageSize);
            
            // 这里简化处理，直接获取所有消息（实际项目中应该使用分页查询）
            List<AiChatMessage> messages = aiChatService.getChatHistory(userId, sessionId);
            
            // 转换为DTO列表
            List<AiChatMessageDto> messageDtos = messages.stream()
                    .map(this::convertToDto)
                    .collect(Collectors.toList());

            // 构建分页响应
            AiChatHistoryResponse response = new AiChatHistoryResponse();
            response.setMessages(messageDtos);
            response.setTotal((long) messages.size());
            response.setTotalPages(1); // 简化处理
            response.setCurrentPage(page);

            return HttpResult.success(response);

        } catch (Exception e) {
            log.error("获取聊天历史失败", e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取聊天历史失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的所有会话
     */
    @GetMapping("/sessions")
    @Operation(summary = "获取用户会话列表", description = "获取用户的所有AI聊天会话ID列表")
    public HttpResult<List<String>> getUserSessions(@RequestParam Long userId) {
        try {
            if (userId == null) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "用户ID不能为空");
            }

            log.info("获取用户会话列表，用户ID: {}", userId);

            List<String> sessions = aiChatService.getUserSessions(userId);
            return HttpResult.success(sessions);

        } catch (Exception e) {
            log.error("获取用户会话列表失败", e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取会话列表失败: " + e.getMessage());
        }
    }

    /**
     * 开始新会话
     */
    @PostMapping("/new-session")
    @Operation(summary = "开始新会话", description = "生成新的AI聊天会话ID")
    public HttpResult<String> startNewSession(@RequestParam Long userId) {
        try {
            if (userId == null) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "用户ID不能为空");
            }

            String sessionId = aiChatService.generateSessionId();
            log.info("创建新会话，用户ID: {}, 会话ID: {}", userId, sessionId);

            return HttpResult.success(sessionId);

        } catch (Exception e) {
            log.error("创建新会话失败", e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "创建会话失败: " + e.getMessage());
        }
    }

    /**
     * 将实体转换为DTO
     */
    private AiChatMessageDto convertToDto(AiChatMessage message) {
        AiChatMessageDto dto = new AiChatMessageDto();
        dto.setMessageId(message.getId());
        dto.setContent(message.getMessageContent());
        dto.setMessageType(message.getMessageType().name());
        dto.setTimestamp(message.getTimestamp().format(DATE_TIME_FORMATTER));
        return dto;
    }
}